from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
import logging
import time

logger = logging.getLogger(__name__)

class AppParameters(models.Model):
    type = models.CharField(max_length=16)
    name = models.CharField(max_length=32, primary_key=True)
    value = models.CharField(max_length=256, null=True)
    value_int = models.IntegerField(null=True)

class AppKey(models.Model):
    appkey = models.CharField(unique=True, max_length=256)
    status = models.CharField(max_length=32)

class Category(models.Model):
    name = models.CharField(unique=True, max_length=32)
    desc = models.CharField(max_length=256)

    #users = models.ManyToManyField('UserProfile')

class Language(models.Model):
    code = models.CharField(primary_key=True, max_length=16)
    desc = models.CharField(max_length=256)

    #users = models.ManyToManyField('UserProfile')

class Phrase(models.Model):
    phrase = models.CharField(null=False, max_length=4096)

    category = models.ForeignKey(Category)
    language = models.ForeignKey(Language)

    def __unicode__(self):
        return '{pk: ' + str(self.pk) + ', phrase: ' + self.phrase + '}'

class Translation(models.Model):
    translation = models.CharField(null=False, max_length=4096)

    phrase = models.ForeignKey(Phrase)
    language = models.ForeignKey(Language)

    def __unicode__(self):
        return '{pk: ' + str(self.pk) + ', translation: ' + self.translation + '}'

class PhraseOfDay(models.Model):
    day = models.DateTimeField(null=False)
    phrase = models.ForeignKey(Phrase)

    #users = models.ManyToManyField('UserProfile')

    def __unicode__(self):
        return '{pk: ' + str(self.pk) + ', day: ' + self.day.isoformat() + ', phrase: ' + str(self.phrase) + '}'

class UserProfile(models.Model):
    # This field is required.
    user = models.OneToOneField(User)
    
    # Other fields here
    categories = models.ManyToManyField(Category)
    languages = models.ManyToManyField(Language)
    phrases_of_day = models.ManyToManyField(PhraseOfDay)

def create_user_profile(sender, instance, created, **kwargs):
    logger.debug('create_user_profile; ')
    if created:
        logger.debug('create_user_profile; creating %s', instance)
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)


